package main.controller;

import main.BodySegSample;
import main.PathUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Map;

@RestController
public class SynthesisController {
    @PostMapping("/api/synthesis")
    public String doSynthesis(HttpServletRequest request) {
        Map<String, String[]> paramMap = request.getParameterMap();
        String backgroundImagePath = null, foregroundImagePath = null;
        if (paramMap.containsKey("bg")) {
            backgroundImagePath = paramMap.get("bg")[0];
        }
        if (paramMap.containsKey("fg")) {
            foregroundImagePath = paramMap.get("fg")[0];
        }

        if (backgroundImagePath == null || foregroundImagePath == null) {
            return "error";
        }

        //TODO: from the foregroundImage & baidu api, get the result from baidu api
        String destFilePath = null;
        try {
            destFilePath = BodySegSample.doSeg(PathUtil.PathPrefix + foregroundImagePath);
            String bgImagePath = PathUtil.PathPrefix + backgroundImagePath;
            BufferedImage bgImage = ImageIO.read(new File(bgImagePath));
            int bgWidth = bgImage.getWidth();
            int bgHeight = bgImage.getHeight();

            BufferedImage destImage = ImageIO.read(new File(destFilePath));
            int destWidth = destImage.getWidth();
            int destHeight = destImage.getHeight();

            if (destWidth > bgWidth || destHeight > bgHeight) {
                float ratioH = (float) destWidth / (float) bgWidth;
                float ratioV = (float) destHeight / (float) bgHeight;

                float ratio = ratioH > ratioV ? ratioH : ratioV;
                ratio = 1 / ratio;
                int newWidth = (int) (destWidth * ratio);
                int newHeight = (int) (destHeight * ratio);

                destImage = BodySegSample.resize(destImage, newWidth, newHeight);
            }

            // now we have bgImage, and destImage, can synthesis!
//            for (int x = 0; x < destImage.getWidth(); ++x) {
//                for (int y = 0; y < destImage.getHeight(); ++y) {
//                    int value = destImage.getRGB(x, y);
//                    if ((value & 0xFF000000) == 0xFF000000) {
//                        bgImage.setRGB(x, y, value);
//                    }
//                    else {
//
//                    }
//                }
//            }
            // process synthesis
            File newFile = new File(PathUtil.PathPrefix + "dest.png");
            ImageIO.write(destImage, "png", newFile);
        }
        catch (Exception e) {
            System.out.println(e.toString());
        }

        return "dest.png";
    }
}

